<?php


namespace app\verify\model\logic;


use app\common\exception\BizException;
use think\facade\Cache;
use think\helper\Str;

class IndexLogic
{
    /**
     * 短信（国内号）发送验证码
     * @param array $param
     * @return array
     */
    public function sendMsg(array $param)
    {
        $code = '888888';
        $param['code'] = $code;

        $certificate = md5($param['receiver'].Str::random());

        Cache::set($certificate,$param,60*15);

        return ['certificate' => $certificate];
    }

    /**
     * 短信（国际号）发送验证码
     * @param array $param
     * @return array
     */
    public function sendInternationalMsg(array $param)
    {
        $code = '888888';
        $param['code'] = $code;

        $certificate = md5($param['receiver'].Str::random());

        Cache::set($certificate,$param,60*15);

        return ['certificate' => $certificate];
    }

    /**
     * 邮件发送验证码
     * @param array $param
     * @return boolean
     */
    public function sendEmail(array $param)
    {
        $code = Str::random(6);
        $param['code'] = $code;

        $certificate = md5($param['receiver'].Str::random());

        Cache::set($certificate,$param,60*15);

        return true;
    }

    /**
     * 验证码验证
     * @param array $param
     * @return array
     */
    public function check(array $param)
    {
        $captcha = Cache::get($param['certificate']);

        if($param['code'] !== $captcha['code']) {
            throw new BizException('', CAPTCHA_ERROR);
        }
        if($param['scene'] !== $captcha['scene']) {
            throw new BizException('验证码类型错误', FAILED);
        }

        Cache::rm($param['certificate']);
        $captchaToken = [
            'mobile' => $captcha['receiver'],
            'scene' => $captcha['scene'],
        ];
        $token = md5($captchaToken['mobile'].Str::random().'token');
        Cache::set($token,$captchaToken,60*22);

        return ['token' => $token];
    }
}